package com.wjw.web;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.wjw.bean.Permission;
import com.wjw.dao.PermissionDao;

public class AuthInterceptor extends HandlerInterceptorAdapter{
	
	@Autowired
	private PermissionDao permissiondao;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri=request.getRequestURI();
		System.out.println("authintercetor uri="+uri);
		HttpSession session=request.getSession();
		String path=session.getServletContext().getContextPath();
		List<Permission> permissions=permissiondao.findAll();
		Set<String> uriset =new HashSet<>();
		//查出需要进行判断的全部权限
		for(Permission permission:permissions){
			if(permission.getUrl()!=null&&!"".equals(permission.getUrl())){
				System.out.println("uriset="+path+permission.getUrl());
				uriset.add(path+permission.getUrl());
			}
		}
		if(uriset.contains(uri)){
			Set<String> authPath=new HashSet<>();
			authPath=(Set<String>)session.getAttribute("authUriPath");
			if(authPath.contains(uri)){
				return true;
			}else{
				response.sendRedirect(path+"/error");
				return false;
			}
		}else{
			return true;
		}
		
		
	}
	
}
